var mysql=require("mysql");

var conn_pool=null;

function connect_to_sql(host,port,db_name,uname,upwd){
	conn_pool=mysql.createPool({
	host:host,
	port:port,
	database:db_name,
	user:uname,
	password:upwd});
}

let query = function( sql, values ) {
  // 返回一个 Promise
  return new Promise(( resolve, reject ) => {
    conn_pool.getConnection(function(err, conn) {
      if (err) {
        reject(err);
      } else {
        conn.query(sql, values, (err, result) => {

          if (err) {
            reject(err);
          } else {
            resolve(result);
          }
          // 结束会话
          conn.release();
        })
      }
    })
  });
};

//获取游戏数据
async function get_game_info_by_id(id){
	try{
		var result=await query("select exp,chip,game_vip,status from game where user_id=? limit 1",[id]);
		return {err:0,result};
	}
	catch(err){
		return {err:1};
	}
}

//插入游戏数据
async function insert_game_user(id){
	try{
		var result=await query("insert into game(user_id) values(?)",[id]);
		return {err:0,result};
	}
	catch(err){
		return {err:1};
	}
}

//增加游戏金币数
async function add_game_chip(id,chip_plus){
	try{
		var result=await query("update game set chip=chip+? where user_id=?",[chip_plus,id]);
		return {err:0,result};
	}
	catch(err){
		return {err:1};
	}
}


//获取登录奖励信息
async function get_login_bonues_by_id(id){
	try{
		var result=await query("select bonues,bonues_time,days,status from login_bonues where user_id=? limit 1",[id]);
		return {err:0,result};
	}
	catch(err){
		return {err:1};
	}
}

//插入奖励信息
async function insert_login_bonues(id,bonues,bonues_time){
	try{
		var result=await query("insert into login_bonues(user_id,bonues,bonues_time,days) values(?,?,?,1)",[id,bonues,bonues_time]);
		return {err:0,result};
	}
	catch(err){
		return {err:1};
	}
}

//更新奖励信息
async function update_login_bonues(id,bonues,bonues_time,days){
	try{
		var result=await query("update login_bonues set bonues=?,bonues_time=?,days=?,status=0 where user_id=?",[bonues,bonues_time,days,id]);
		return {err:0,result};
	}
	catch(err){
		return {err:1};
	}
}

//更新领取奖励
async function update_login_bonues_recved(id){
	try{
		var result=await query("update login_bonues set status=1 where user_id=?",[id]);
		return {err:0,result};
	}
	catch(err){
		return {err:1};
	}
}

module.exports={
	connect:connect_to_sql,
	get_game_info_by_id:get_game_info_by_id,
	insert_game_user:insert_game_user,
	get_login_bonues_by_id:get_login_bonues_by_id,
	insert_login_bonues:insert_login_bonues,
	update_login_bonues:update_login_bonues,
	update_login_bonues_recved:update_login_bonues_recved,
	add_game_chip:add_game_chip,
};